package com.baiyun.lovePush.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baiyun.lovePush.entity.Weather;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 接入百度开放平台天气api的工具类
 * @author 派大星
 */
public class WeatherUtils {

    private static final String district_id = "440100";   //设置对方所在城市的编码
    private static final String data_type = "all";
    private static final String ak = "bRKTRrdOpR6F60TOhvHB73ap8lP2";  // 设置ak

    /**
     * 获取天气
     * @author 派大星
     */
    public static Weather getWeather() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> map = new HashMap<>();
        map.put("district_id", district_id);
        map.put("data_type", data_type);
        map.put("ak", ak);

        String res = restTemplate.getForObject(
                "https://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type={data_type}&ak={ak}",
                String.class,
                map);
        System.out.println("天气响应数据:"+res);

        JSONObject json = JSONObject.parseObject(res);
        JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");
        List<Weather> weathers = forecasts.toJavaList(Weather.class);
        JSONObject now = json.getJSONObject("result").getJSONObject("now");
        JSONObject location = json.getJSONObject("result").getJSONObject("location");
        Weather weather = weathers.get(0);
        weather.setText_now(now.getString("text"));
        weather.setTemp(now.getString("temp"));
        weather.setWind_class(now.getString("wind_class"));
        weather.setWind_dir(now.getString("wind_dir"));
        weather.setCity(location.getString("city"));

        return weather;
    }
}
